package com.andertrift.connectors;

import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.lwh.core2.Core2EngineManager;
import com.lwh.core2.Document;
import com.lwh.core2.Sentence;
import com.lwh.core2.api.Core2Exception;
import com.lwh.core2.semantics.Concept;
import com.lwh.core2.semantics.PatternMatch;
import com.lwh.core2.semantics.SatelliteMatch;
import com.lwh.test.Core2Tester;
import com.lwh.util.Util;

public class LingWareHouseConnector {
	private static final String CONFIG_PATH = "C:\\Users\\Mathias\\Desktop\\Core2Test\\EN\\config.xml";

	private static Logger logger = Logger.getLogger(TwitterConnector.class);

	/**
	 * Parses all the files in the in folder with the Core2Tester main program
	 */
	/*public void parseFiles() {
		String[] arguments = new String[] { ROOT + "in", ROOT + "out\\",
				ROOT + "LM\\Lexicon_Salesforce_dot_com_V2.txt",
				ROOT + "LM\\English_SyntaxRules_V2.txt",
				ROOT + "LM\\concept_tree_Salesforce_dot_com_V2.txt",
				ROOT + "LM\\English_SemanticPatterns_Salesforce_dot_com_V2.txt" };
		try {
			Core2Tester.main(arguments);
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
	}*/

	/**
	 * Parses sentence with the Core2Tester main program
	 */
	public String parseSentence(String s) {
		StringBuilder sb = new StringBuilder();
		try {

			Core2EngineManager engine = new Core2EngineManager("Twitter");
			try {
				engine.initialize(CONFIG_PATH);
			} catch (Core2Exception e) {
				Util.logln(e.toString());
				e.printStackTrace();
			}
			Document doc = new Document(s);
			doc.setEngine(engine);
			Sentence sentence = doc.getSentence(0);

			List<PatternMatch> patternMatches = sentence.getSemanticMatches();
			Set<PatternMatch> processedMatches = new HashSet<PatternMatch>();
			for (PatternMatch patternMatch : patternMatches) {
				if (!processedMatches.contains(patternMatch.getId())) {
					processedMatches.add(patternMatch);
				}
			}
			PatternMatch bestMatch = null;
			for (PatternMatch match : processedMatches) {
				if (bestMatch == null || match.getRank() > bestMatch.getRank()){
					bestMatch = match;
				}
			}
			for (SatelliteMatch sm : bestMatch.getMandatorySatellites()) {
				sb.append(sm.getPhraseTxt() + " is ");
				for (List<Concept> cl : sm.getConcepts()) {
					for (Concept c : cl) {
						sb.append("|\"" + c.getLabel() + "\"|" );
					}
				}
				sb.append(" right?");
			}

		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		logger.debug(sb.toString());
		return sb.toString();
	}

}
